import { defineStore } from 'pinia'

export const useThemeStore = defineStore('theme', {
  state: () => ({
    isDark: false, // false: 白天主题, true: 黑夜主题
  }),
  
  getters: {
    // 获取当前主题名称
    themeName: (state) => state.isDark ? '黑夜' : '白天',
    
    // 获取主题相关的CSS变量
    themeVars: (state) => {
      if (state.isDark) {
        return {
          // 黑夜主题
          '--primary-bg': '#1a1a1a',
          '--secondary-bg': '#2d2d2d',
          '--sidebar-bg': '#1e1e1e',
          '--text-primary': '#ffffff',
          '--text-secondary': '#b0b0b0',
          '--border-color': '#404040',
          '--card-bg': '#2d2d2d',
          '--hover-bg': '#3a3a3a',
          '--shadow': '0 2px 8px rgba(0, 0, 0, 0.3)',
        }
      } else {
        return {
          // 白天主题
          '--primary-bg': '#f5f7fa',
          '--secondary-bg': '#ffffff',
          '--sidebar-bg': 'linear-gradient(135deg, #667eea 0%, #764ba2 100%)',
          '--text-primary': '#2c3e50',
          '--text-secondary': '#7f8c8d',
          '--border-color': '#e9ecef',
          '--card-bg': '#ffffff',
          '--hover-bg': '#f8f9fa',
          '--shadow': '0 2px 8px rgba(0, 0, 0, 0.1)',
        }
      }
    }
  },
  
  actions: {
    // 切换主题
    toggleTheme() {
      console.log('切换主题，当前状态:', this.isDark)
      this.isDark = !this.isDark
      console.log('切换后状态:', this.isDark)
      this.applyTheme()
    },
    
    // 设置主题
    setTheme(isDark) {
      this.isDark = isDark
      this.applyTheme()
    },
    
    // 应用主题到CSS变量
    applyTheme() {
      console.log('应用主题，isDark:', this.isDark)
      const root = document.documentElement
      const body = document.body
      
      // 设置data-theme属性
      if (this.isDark) {
        root.setAttribute('data-theme', 'dark')
        body.classList.add('dark-theme')
        body.classList.remove('light-theme')
        console.log('应用黑夜主题')
      } else {
        root.setAttribute('data-theme', 'light')
        body.classList.add('light-theme')
        body.classList.remove('dark-theme')
        console.log('应用白天主题')
      }
      
      // 应用CSS变量到DOM
      const vars = this.themeVars
      Object.entries(vars).forEach(([key, value]) => {
        root.style.setProperty(key, value)
      })
      
      console.log('CSS变量已应用:', vars)
      
      // 保存到localStorage
      localStorage.setItem('theme', this.isDark ? 'dark' : 'light')
    },
    
    // 初始化主题
    initTheme() {
      const savedTheme = localStorage.getItem('theme')
      if (savedTheme) {
        this.isDark = savedTheme === 'dark'
      } else {
        // 根据系统偏好设置默认主题
        this.isDark = window.matchMedia('(prefers-color-scheme: dark)').matches
      }
      this.applyTheme()
    }
  },
  
  persist: {
    key: 'theme',
    storage: localStorage,
    paths: ['isDark']
  }
})
